SET(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS ON)
MESSAGE(STATUS "Load tool chain for Cortex")
# invoke by -DCMAKE_TOOLCHAIN_FILE
# tool chain profix
MESSAGE("SYSTEM name ${CMAKE_HOST_SYSTEM_NAME}")
IF(NOT L_TOOLCHAIN_PATH)
    #IF(${CMAKE_HOST_SYSTEM_NAME} MATCHES  "Windows")
    IF(WIN32)
    SET(L_TOOLCHAIN_PATH "C:/unsoft/arm-none-gcc/2018q2")
    SET(L_EXE_SUFFIX ".exe")
    ELSE()
    SET(L_TOOLCHAIN_PATH "/opt/armgcc/none/gcc-arm-none-eabi-7-2018-q2-update")
    SET(L_EXE_SUFFIX)
    ENDIF()
    MESSAGE(STATUS "No L_TOOLCHAIN_PREFIX specified, using default:  ${L_TOOLCHAIN_PATH}")
ENDIF()

IF (NOT L_TOOLCHAIN_PREFIX)
    SET(L_TOOLCHAIN_PREFIX "arm-none-eabi-")
    MESSAGE(STATUS "No L_TOOLCHAIN_PREFIX specified, using default: ${L_TOOLCHAIN_PREFIX}")
ENDIF()


SET(L_TOOLCHAIN_BIN_DIR ${L_TOOLCHAIN_PATH}/bin)

# set the base system informations
SET(CMAKE_SYSTEM_NAME Generic CACHE INTERNAL "system name")
SET(CMAKE_SYSTEM_PROCESSOR arm CACHE INTERNAL "processor")

# compiler settings
SET(CMAKE_C_COMPILER ${L_TOOLCHAIN_BIN_DIR}/${L_TOOLCHAIN_PREFIX}gcc${L_EXE_SUFFIX} CACHE INTERNAL "")
SET(CMAKE_CXX_COMPILER ${L_TOOLCHAIN_BIN_DIR}/${L_TOOLCHAIN_PREFIX}g++${L_EXE_SUFFIX} CACHE INTERNAL "")
SET(CMAKE_ASM_COMPILER ${L_TOOLCHAIN_BIN_DIR}/${L_TOOLCHAIN_PREFIX}as${L_EXE_SUFFIX} CACHE INTERNAL "")
SET(CMAKE_OBJCOPY ${L_TOOLCHAIN_BIN_DIR}/${L_TOOLCHAIN_PREFIX}objcopy${L_EXE_SUFFIX} CACHE INTERNAL "")
SET(CMAKE_OBJDUMP ${L_TOOLCHAIN_BIN_DIR}/${L_TOOLCHAIN_PREFIX}objdump${L_EXE_SUFFIX} CACHE INTERNAL "")

# append some flags
# default cflags and cxx flags  -specs=nosys.specs -fno-builtin
SET(U_C_FLAGS "-mthumb -mcpu=cortex-m3 -Wall -std=gnu99 -fdata-sections -ffunction-sections -specs=nosys.specs --specs=nano.specs")
SET(U_ASM_FLAGS "-mthumb -mcpu=cortex-m3")
SET(U_LINK_FLAGS "-mcpu=cortex-m3 -nostartfiles -Wl,--gc-sections -mthumb  ")

SET(CMAKE_C_FLAGS "${U_C_FLAGS}" CACHE INTERNAL "c compiler flags")
SET(CMAKE_CXX_FLAGS " ${U_C_FLAGS}" CACHE INTERNAL "cxx compiler flags")
SET(CMAKE_ASM_FLAGS " ${U_ASM_FLAGS}" CACHE INTERNAL "asm compiler flags")
SET(CMAKE_EXE_LINKER_FLAGS "${U_LINK_FLAGS}" CACHE INTERNAL "exe link flags")


# function, here will not to use the local variables
MACRO(M_GENERATE_MAP name)
    SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-M=${name}.map")
    MESSAGE(STATUS "Add Map file to link ${name}.map")
ENDMACRO()

#  add link file to the target
MACRO(M_ADD_LINK_FILE name)
    #
    SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -T${name}")
    MESSAGE(STATUS "Link file: ${name}")
ENDMACRO()

# objcopy the bin file and hex file
MACRO(M_GENERATE_BIN_HEX name)
    MESSAGE(STATUS "Generate bin file ${name}")
    ADD_CUSTOM_COMMAND(TARGET ${name}.elf POST_BUILD COMMAND ${CMAKE_OBJCOPY} ARGS -Oihex ${name}.elf ${name}.hex)
    ADD_CUSTOM_COMMAND(TARGET ${name}.elf POST_BUILD COMMAND ${CMAKE_OBJCOPY} ARGS -Obinary ${name}.elf ${name}.bin)
ENDMACRO()





